<?php

namespace Apps\AppApi\Method\User;

use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Models\UserAttribute;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\UserBase;
use Apps\Common\Models\UserFollow;
use Apps\Common\Libs\PicUrl;

/**
 * 专家详情（基本信息）
 */
class ExpertInfo extends BaseMethod
{
    public function run()
    {
    	$user_id = intval($this->getDataItem('user_id', 0));
		$expert_id = intval($this->getDataItem('expert_id', 0));

//		$expert_id = 289;

		if ($expert_id < 1) {
			return $this->errorLog(ResultStatus::URL_PARAM_CANNOT_EMPTY, '缺少必传参数！');
		}

		$columns = ['user_id', 'user_nickname', 'user_cover', 'expert_follow_count', 'persional_sign'];
		if ($UserBase = UserBase::query()->columns($columns)->where('user_expert = 1 and user_id = ' . $expert_id)->execute()->getFirst()) {
			$info = $UserBase->toArray();
			$info['user_cover'] = PicUrl::ActivityCover($info['user_cover'], $this->getDi());

			if ($userAttribute = UserAttribute::findFirst('attr_type = 103 and attr_state = 1 and user_id = ' . $expert_id)) {
				$attr_value_json = $userAttribute->attr_value_json;
			} else {
				$attr_value_json = [];
			}
			$info['persional_sign'] = $info['persional_sign'] ? unserialize(base64_decode($info['persional_sign'])) : '';
			$attr_value_json = $attr_value_json ? json_decode($attr_value_json) : [];
			$info['experience'] = $attr_value_json->experience ?: ''; // 从业经验
			$info['experttitle'] = $attr_value_json->experttitle ?: ''; // 擅长领域
			$info['field'] = $attr_value_json->field ?: []; // 专家头衔(array)

			if ($user_id > 0) {
				$info['is_follow'] = (new UserFollow())->is_follow($user_id, $expert_id, 2) ? '1' : '0';
			} else {
				$info['is_follow'] = '0';
			}

			// 回答问题数
			$result = (new UserBase())->getReadConnection()->query("SELECT count(*) c FROM
(SELECT count(*) FROM question_answer WHERE answer_state = 1 AND user_id = {$expert_id} GROUP BY question_id) a;");
			$count = $result->fetch();
			$info['question_count'] = $count['c'];
		} else {
			return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, '用户不存在或不是专家');
		}
		$this->setResult($info);
    }
}